import $store from "../store/index";
import router from './index'
import { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
NProgress.configure({ showSpinner: false })// NProgress Configuration
import { getToken, setStorage, getStorage } from '../utils/auth'
import Config from '../config';
import { getMeneData } from '../api/login.js'
import Layout from '../views/Layout/Layout.vue'
import Content from '../views/Layout/Content.vue'
const modules = import.meta.glob("../views/**/**.vue");  // vite全局引入

const loadView = (parentName: string, view: string) => { // 路由懒加载
    // return () => import(`@/views/${view}.vue`)
    let path = `../views/${parentName}/${view}.vue` // 动态三级菜单
    return modules[path]
}

const loadMenus = (next: NavigationGuardNext, to: RouteLocationNormalized) => {
    getMeneData().then((res) => {
        let result: Array<any> = res;
        let asyncRouter = generateRoute(result, null)
        $store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
            router.addRoute(asyncRouter[0])
            next({ ...to, replace: true })// hack方法 确保addRoutes已完成
        })
    })
}

const generateRoute = (routers: Array<any>, parentName: string): Array<RouteRecordRaw> => { // 遍历后台传来的路由字符串，转换为组件对象
    const accessedRouters = routers.filter(routes => {
        if (routes.component) {
            if (routes.component === 'Layout') {                        // Layout组件特殊处理  固定一级菜单
                routes.component = Layout
            } else if (routes.component === 'Content') {                       // Content组件特殊处理 固定二级菜单
                routes.component = Content
            } else {
                routes.component = loadView(parentName, routes.component)
            }
        }
        if (routes.children && routes.children.length) {
            routes.children = generateRoute(routes.children, routes.name)
        }
        return true
    })
    return accessedRouters
}

router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title + ' - ' + Config.webName
    }
    NProgress.start() // start progress bar
    if (getToken()) {
        // 已登录且要跳转的页面是'/'重定向到登录页
        if (to.path == '/') {
            //removeToken();
            next({ path: '/Home' })
            NProgress.done() // finish progress bar
        } else
            if ($store.state.user.routers.length == 0) {
                //缓存没有数据
                loadMenus(next, to)
            } else if ($store.getters.loadMenus) {//登录后重新拉取菜单
                $store.dispatch('updateLoadMenus')//改成false，防止死循环
                loadMenus(next, to)
            } else if (to.matched.length === 0) {
                next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
            } else {
                if (to.path === '/404') { next() }
                else if (getStorage('currentPath') && to.path !== getStorage('currentPath')) {
                    let routes = router.options.routes
                    setStorage("currentMenu", routes[0].path);
                    setStorage("SideMenu", JSON.stringify(routes[0].children));
                    setStorage("currentPath", '/Home');
                    next('/Home')
                } else {
                    next()
                }

            }
    } else {
        if (to.path === '/login') { //这就是跳出循环的关键
            next()
        } else {
            next('/login')// 全部重定向到登录页
            NProgress.done() // finish progress bar
        }
    }
})

router.afterEach(() => {
    NProgress.done() // finish progress bar
});

export default router;